#include "log.hpp"

void Logger::LoggerInit()
{
    pthread_mutex_init(&lock, nullptr);
    pthread_cond_init(&HaveMessgae, nullptr);
    pthread_create(&pthread_id, nullptr, threadfunction, ((void *)this));
}


void* Logger::threadfunction(void *arg)
{
    Logger *logger = (Logger *)arg;

    while(1){
        pthread_mutex_lock(&logger->lock);

        while(logger->MessageQueue.empty()){
            pthread_cond_wait(&logger->HaveMessgae, &logger->lock);
        }
        logger->WriteLog();
        pthread_mutex_unlock(&logger->lock);
    }
}

void Logger::AddMessage(const std::string &msg){
    char LogBuf[512] = {0};
    time_t now = time(nullptr);             // 获取当前时间
    struct tm *cur_time = localtime(&now);  // 将当前时间转化为本地时间


    sprintf(LogBuf, "Time: [ %04d-%02d-%02d %02d:%02d:%02d ]\tPthread: [0x%04x]\tContent: %s\n",
            cur_time->tm_year + 1900,
            cur_time->tm_mon + 1,
            cur_time->tm_mday,
            cur_time->tm_hour,
            cur_time->tm_min,
            cur_time->tm_sec,
            pthread_self(),
            msg.c_str());


    pthread_mutex_lock(&lock);
    
    MessageQueue.push_back(std::string(LogBuf));
    
    pthread_mutex_unlock(&lock);

    pthread_cond_signal(&HaveMessgae);
}

void Logger::WriteLog(){
    const std::string &content = MessageQueue.front();
    file_out << content;
    MessageQueue.pop_front();
}